package com.arelikebrothers.demo.concurrent.jdk;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by lennon on 03/05/2017.
 */
public class SimpleDateformatOk {

    private static final ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<>();
//    private static final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static class ParseDate implements Runnable {
        int i;

        public ParseDate(int i) {
            this.i = i;
        }

        @Override
        public void run() {


            try {
                SimpleDateFormat fmt = Optional.ofNullable(tl.get())
                        .orElseGet(()->{
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            tl.set(dateFormat);
                            return dateFormat;
                        });
                Date date = fmt.parse("2017-05-03 20:" + i % 60 + ":" + (i % 60));
                System.out.println(i + ": " + date);
            } catch (ParseException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } finally {
                // 防止内存泄露
                tl.remove();
            }
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 100000; i++) {
            exec.submit(new ParseDate(i));
        }
        exec.shutdown();
    }
}
